/**
 ****************************************************************************************
 *
 * @file main.c
 *
 * @brief Main Entry of the application.
 *
 ****************************************************************************************
 */

#include "bledef.h"
#include "drvs.h"
#include "app.h"
#include "sftmr.h"
#include "batt.h"
#include "keys.h"
#include "dbg.h"
#include "app_user.h"


/*
 * DEFINES
 ****************************************************************************************
 */


/*
 * FUNCTIONS
 ****************************************************************************************
 */
uint32_t g_store_os;
extern void user_procedure(void);

static void sysInit(void)
{
    iwdt_disable();

    rcc_ble_en();
    rcc_adc_en();

    rcc_fshclk_set(FSH_CLK_DPSC42);

    #if (CFG_POWEROFF)
    core_release_io_latch();
    #endif
}

static void devInit(void)
{
    uint16_t rsn = rstrsn();

    uint32_t store_mac = RD_32(FLASH_BASE + BT_MAC_STORE_OFFSET);
    
    if (store_mac != 0xFFFFFFFF)
    {
        write32p(ble_dev_addr.addr, store_mac);
    }

    g_store_os = RD_32(FLASH_BASE + OS_STORE_OFFSET);
    
    dbgInit();
    debug("Start(rsn:%X, mac:%08X, os:%d)...\r\n", rsn, store_mac, g_store_os);

//    #if (CFG_SFT_TMR)
//    sftmr_init();
//    #endif
    
    batt_init();
    keys_init();

    // Init BLE App
    app_init(rsn);
}

int main(void)
{
    sysInit();
    devInit();

    // Global Interrupt Enable
    GLOBAL_INT_START();

    // main loop
    while (1)
    {
        // Schedule Messages & Events
        ble_schedule();
        
//        #if (CFG_SFT_TMR)
//        // SoftTimer Polling
//        sftmr_schedule();
//        #endif //(LED_PLAY)
        
        // User's Procedure
        user_procedure();
    }
}
